package com.chinasoft04.mall.controller;


import com.chinasoft04.mall.dto.Rbody;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@CrossOrigin
@AllArgsConstructor
@RequestMapping("/api/private/v1")
public class UploadController {


    @PostMapping("/upload")
    public Rbody uploadImage(HttpServletRequest request,MultipartFile file) throws IOException {
        Rbody rbody = new Rbody();

        String realPath = request.getSession().getServletContext().getRealPath("/");


        System.out.println(realPath);

        String filename = UUID.randomUUID().toString();

        File dir = new File(realPath+"tmp_uploads");
        dir.mkdir();

        File newFile = new File(realPath +"tmp_uploads/"+ filename+".png");

        file.transferTo(newFile);


        Map<String , String> data = new HashMap<>();
        data.put("tmp_path","tmp_uploads/"+filename+".png");
        data.put("url","http://127.0.0.1:8888/tmp_uploads/"+filename+".png");

        rbody.setData(data);
        rbody.getMeta().setMsg("上传成功");
        rbody.getMeta().setStatus(200);



        return rbody;
    }
}
